import logging
from django.views.decorators.http import require_GET
from common.utils.decorator import response_wrapper, validate_form
from common.utils.api import token_required
from common.dwc.maestro import op_analysis_handler as op_handler
from event_rule.dwc.op_event_rule.rule_config import CONFIG
from common.permission.handler import process_resp_items, get_key_mapper
from common.utils.export import export_file
from common.mg_core import mg
from .form import (
    GeneralReport,
    RechargeAnalysisForm,
    OpUserAnalysisForm,
    DailyAnalysisForm,
    WithdrawAnalysisForm
)

_LOGGER = logging.getLogger(__name__)


@require_GET
@response_wrapper
@token_required
@validate_form(GeneralReport)
def get_general_report(req, cleaned_data):
    merchant_name = req.merchant_name
    target_event_id = cleaned_data['target_event_id']
    chn_filter_list = cleaned_data['chn_filter_list']
    report = op_handler.op_graph_report_handler(merchant_name, target_event_id, chn_filter_list)
    return report


@require_GET
@response_wrapper
@token_required
@validate_form(OpUserAnalysisForm)
def get_op_user_analysis(req, cleaned_data):
    merchant_name, role_id = req.merchant_name, req.merchant_role['id']
    time_range = cleaned_data['time_range']
    user_type = cleaned_data['user_type']
    interval_type = cleaned_data['interval_type'] or 'day'
    chn_filter_list = cleaned_data['chn_filter_list']
    chn_device_type = cleaned_data['chn_device_type'] or 'all'
    merge_report = cleaned_data['merge_by_interval_type'] or False
    sort_by = cleaned_data['sort_by'] or '-day'
    size, page = cleaned_data['size'], cleaned_data['page']
    to_export_file = cleaned_data['to_export_file']
    condition = dict(updated_at={'$gte': time_range[0], '$lt': time_range[1]}, interval_type=interval_type,
                     _chn_device_type=chn_device_type)
    if len(chn_filter_list) > 0 and chn_device_type == 'all':
        del condition['_chn_device_type']
    condition['_chn'] = {'$in': chn_filter_list} if chn_filter_list else 'all'
    disable_paginate = False if not to_export_file else True
    summarized_report, total_count = mg.get_report(merchant_name, 'op_user_report', condition, sort_by, page=page,
                                                   size=size, disable_paginate=disable_paginate, user_type=user_type,
                                                   event_rule=CONFIG['user'], time_interval_type=interval_type,
                                                   merge_report=merge_report)
    key_mapper = get_key_mapper(merchant_name, '3005', role_id, required_chn=True if chn_filter_list else False,
                                time_interval_type=interval_type)
    resp_items = process_resp_items(summarized_report, key_mapper)
    if to_export_file:
        return export_file(req, resp_items, key_mapper, file_name='op_user_report')
    return dict(total_count=total_count, list=resp_items, key_mapper=key_mapper)


@require_GET
@response_wrapper
@token_required
@validate_form(RechargeAnalysisForm)
def get_recharge_analysis(req, cleaned_data):
    merchant_name = req.merchant_name
    role_id = req.merchant_role['id']
    time_range = cleaned_data['time_range']
    time_interval_type = cleaned_data['time_interval_type'] or 'day'
    chn_filter_list = cleaned_data['chn_filter_list']
    merge_report = cleaned_data['merge_by_interval_type'] or False
    user_type = cleaned_data['user_type']
    sort_by = cleaned_data['sort_by'] or '-updated_at'
    size, page = cleaned_data['size'], cleaned_data['page']
    to_export_file = cleaned_data['to_export_file']
    condition = dict(updated_at={'$gte': time_range[0], '$lt': time_range[1]}, interval_type=time_interval_type)
    condition['_chn'] = {'$in': chn_filter_list} if chn_filter_list else 'all'
    disable_paginate = False if not to_export_file else True
    recharge_reports, total_count = mg.get_report(merchant_name, 'op_recharge_report', condition, sort_by,
                                                  page=page, size=size, disable_paginate=disable_paginate,
                                                  user_type=user_type,
                                                  event_rule=CONFIG['recharge'], time_interval_type=time_interval_type,
                                                  merge_report=merge_report)
    key_mapper = get_key_mapper(merchant_name, '3006', role_id, time_interval_type=time_interval_type,
                                required_chn=True if chn_filter_list else False)
    resp_items = process_resp_items(recharge_reports, key_mapper)
    if to_export_file:
        return export_file(req, resp_items, key_mapper, file_name='recharge_analysis')
    return dict(total_count=total_count, list=resp_items, key_mapper=key_mapper)


@require_GET
@response_wrapper
@token_required
@validate_form(DailyAnalysisForm)
def get_daily_analysis(req, cleaned_data):
    merchant_name = req.merchant_name
    role_id = req.merchant_role['id']
    time_range = cleaned_data['time_range']
    sort_by = cleaned_data['sort_by'] or '-updated_at'
    size, page = cleaned_data['size'], cleaned_data['page']
    to_export_file = cleaned_data['to_export_file']
    condition = dict(updated_at={'$gte': time_range[0], '$lt': time_range[1]})
    disable_paginate = False if not to_export_file else True
    daily_reports, total_count = mg.get_report(merchant_name, 'op_daily_report', condition, sort_by, page=page,
                                               size=size, disable_paginate=disable_paginate)
    key_mapper = get_key_mapper(merchant_name, '3007', role_id)
    resp_items = process_resp_items(daily_reports, key_mapper)
    if to_export_file:
        return export_file(req, resp_items, key_mapper, file_name='daily_analysis')
    return dict(total_count=total_count, list=resp_items, key_mapper=key_mapper)


@require_GET
@response_wrapper
@token_required
def get_pay_type(req):
    resp_items = op_handler.get_pay_type_list()
    return dict(pay_type_list=resp_items)


@require_GET
@response_wrapper
@token_required
@validate_form(WithdrawAnalysisForm)
def get_withdraw_analysis(req, cleaned_data):
    merchant_name, role_id = req.merchant_name, req.merchant_role['id']
    time_range = cleaned_data['time_range']
    user_type = cleaned_data['user_type']
    interval_type = cleaned_data['time_interval_type'] or 'day'
    chn_filter_list = cleaned_data['chn_filter_list']
    pay_channel_list = cleaned_data['pay_channel_list']
    merge_report = cleaned_data['merge_by_interval_type'] or False
    sort_by = cleaned_data['sort_by'] or '-day'
    size, page = cleaned_data['size'], cleaned_data['page']
    to_export_file = cleaned_data['to_export_file']
    condition = dict(updated_at={'$gte': time_range[0], '$lt': time_range[1]}, interval_type=interval_type)
    condition['_chn'] = {'$in': chn_filter_list} if chn_filter_list else 'all'
    condition['sub_type'] = {'$in': pay_channel_list} if pay_channel_list else 'all'
    disable_paginate = False if not to_export_file else True
    custom_value_by_field = None
    if merge_report:
        custom_value_by_field = {"_chn": "汇总", "sub_type": "汇总"}
    report, total_count = mg.get_report(merchant_name, 'op_withdraw_report', condition, sort_by, page=page, size=size,
                                        disable_paginate=disable_paginate, user_type=user_type,
                                        event_rule=CONFIG['withdraw'], time_interval_type=interval_type,
                                        merge_report=merge_report,
                                        custom_value_by_field=custom_value_by_field)
    key_mapper = get_key_mapper(merchant_name, '3008', role_id, required_chn=True if chn_filter_list else False,
                                required_pay_channel=True if pay_channel_list else False,
                                time_interval_type=interval_type)
    resp_items = process_resp_items(report, key_mapper)
    if to_export_file:
        return export_file(req, resp_items, key_mapper, file_name='op_withdraw_report')
    return dict(total_count=total_count, list=resp_items, key_mapper=key_mapper)
